package com.iflytek.uc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.iflytek.uc.dao.EntityTypeDao;
import com.iflytek.uc.domain.EntityType;
import com.iflytek.uc.domain.EntityType.EntityCategory;
import com.iflytek.uc.domain.Relation;
import com.iflytek.uc.exceptions.DuplicateKeyException;
import com.iflytek.uc.service.EntityTypeService;

public class EntityTypeServiceImpl implements EntityTypeService {
	
	private EntityTypeDao entityTypeDao;
	
	public void setEntityTypeDao(EntityTypeDao entityTypeDao) {
		this.entityTypeDao = entityTypeDao;
	}

	public List<EntityType> getEntityTypes() {
		return entityTypeDao.getEntityTypes();
	}

	public EntityType getEntityTypeByName(String name) {
		return entityTypeDao.getEntityTypeByName(name);
	}

	public List<EntityType> getRootEntityTypes() {
		List<EntityType> types = getEntityTypes();
		return filteRootEntityTypes(types);
	}
	
	private List<EntityType> filteRootEntityTypes(List<EntityType> types) {
		List<EntityType> r = new ArrayList<EntityType>();
		for (EntityType type : types) {
			boolean isRoot = true;
			List<Relation> relations = getParentRelations(type.getName());
			for (Relation relation : relations) {
				if (!StringUtils.equals(relation.getParent().getName(), type.getName())) {
					isRoot = false;
					break;
				}
			}
			
			if (isRoot) {
				r.add(type);
			}
		}
		return r;
	}

	public List<EntityType> getRootEntityTypes(EntityCategory category) {
		List<EntityType> types = entityTypeDao.getEntityTypesByCategory(category);
		return filteRootEntityTypes(types);
	}

	public EntityType createEntityType(String name, EntityCategory category,
			String displayName, int displayOrder, String icon16)
			throws DuplicateKeyException {
		// TODO Auto-generated method stub
		return null;
	}

	public void updateEntityType(String name, EntityCategory category,
			String displayName, int displayOrder, String icon16)
			throws DuplicateKeyException {
		// TODO Auto-generated method stub

	}

	public void deleteEntityType(String name) {
		// TODO Auto-generated method stub

	}

	public List<Relation> getParentRelations(String name) {
		return entityTypeDao.getParentRelations(name);
	}

	public List<Relation> getChildRelations(String name) {
		return entityTypeDao.getChildRelations(name);
	}

}
